﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MasterDetailTemplate.Models;
using MasterDetailTemplate.Services;
using MasterDetailTemplate.Services.Implementations;
using Xamarin.Forms.Extended;

namespace MasterDetailTemplate.ViewModels
{
    /// <summary>
    /// 主页的ViewModel
    /// </summary>
    public class HomePageViewModel : ViewModelBase
    {
        /// <summary>
        /// 根导航服务。
        /// </summary>
        private IRootNavigationService _rootNavigationService;

        /// <summary>
        /// 内容导航服务。
        /// </summary>
        private IContentNavigationService _contentNavigationService;

        private IEventStorage _eventStorage;

        private IHistoryTodayService _historyTodayService;

        private String _onehistory;

        public String OneHistory
        {
            get => _onehistory;
            set => Set(nameof(OneHistory), ref _onehistory, value);
        }

        private HistoryToday _historyToday;

        public HistoryToday HistoryToday
        {
            get => _historyToday;
            set => Set(nameof(HistoryToday), ref _historyToday, value);
        }

        /// <summary>  
        /// 把历史上的今天逐条放入Collection中  
        /// </summary>  
        public async void AddToday()
        {
            var historytodayList = await _historyTodayService.GetTodayAsync();
            int size = historytodayList.Count;
            Random rd = new Random();
            var num = rd.Next(0, size);
            HistoryToday = historytodayList[num - 1];
            String titie = HistoryToday.title;
            string[] words = titie.Split(':');
            OneHistory = words[1];
        }

        /// <summary>
        /// 纪念日事件集合。
        /// </summary>
        private InfiniteScrollCollection<Event> _anniversaryDayCollection;

        /// <summary>
        /// 纪念日事件集合。
        /// </summary>
        public InfiniteScrollCollection<Event> AnniversaryDayCollection
        {
            get { return _anniversaryDayCollection; }
            set
            {
                _anniversaryDayCollection = value;
                NotifyPropertyChanged();
            }
        }

        /// <summary>
        /// 倒数日事件集合。
        /// </summary>
        private InfiniteScrollCollection<Event> _countdownDayCollection;

        /// <summary>
        /// 倒数日事件集合。
        /// </summary>
        public InfiniteScrollCollection<Event> CountdownDayCollection
        {
            get { return _countdownDayCollection; }
            set
            {
                _countdownDayCollection = value;
                NotifyPropertyChanged();
            }
        }

        /// <summary>
        /// 所有重要的日期集合
        /// </summary>
        private InfiniteScrollCollection<Event> _allImportEventCollection;

        public InfiniteScrollCollection<Event> AllImportEventCollection
        {
            get { return _allImportEventCollection; }
            set
            {
                _allImportEventCollection = value;
                NotifyPropertyChanged();
            }
        }


        /// <summary>
        /// 属性改变变量。
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// 监控属性改变函数。
        /// </summary>
        /// <param name="propertyName">属性名</param>
        protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }


        /// <summary>
        /// 页面显示命令。
        /// </summary>
        public RelayCommand PageAppearingCommand =>
            _pageAppearingCommand ?? (_pageAppearingCommand =
                new RelayCommand(async () =>
                {
                    await PageAppearingCommandFunction();
                }));

        /// <summary>
        /// 页面显示命令。
        /// </summary>
        public RelayCommand _pageAppearingCommand;

        /// <summary>
        /// 页面显示命令函数。
        /// </summary>
        public async Task PageAppearingCommandFunction()
        {
            AnniversaryDayCollection.Clear();
            CountdownDayCollection.Clear();
            AllImportEventCollection.Clear();
            await AnniversaryDayCollection.LoadMoreAsync();
            await CountdownDayCollection.LoadMoreAsync();
            await AllImportEventCollection.LoadMoreAsync();

            AddToday();
        }

        /// <summary>
        /// 事件点击命令。
        /// </summary>
        public RelayCommand<Event> EventTappedCommand =>
            _eventTappedCommand ?? (_eventTappedCommand =
                new RelayCommand<Event>(async @event =>
                    await EventTappedCommandFunction(@event)));

        /// <summary>
        /// 事件点击命令。
        /// </summary>
        private RelayCommand<Event> _eventTappedCommand;

        public async Task EventTappedCommandFunction(Event eEvent) =>
            await _contentNavigationService.NavigateToAsync(
                ContentNavigationConstants.AnniversaryDetailPage, eEvent);


        /// <summary>
        /// 添加日期。
        /// </summary>
        private RelayCommand _addEventCommamd;

        /// <summary>
        /// 添加日期。
        /// </summary>
        public RelayCommand AddEventCommand =>
            _addEventCommamd ?? (_addEventCommamd = new RelayCommand(
                async () => {
                    await AddEventCommandFunction();
                }));

        public async Task AddEventCommandFunction()
        {
            await _contentNavigationService.NavigateToAsync(
                ContentNavigationConstants.AddEventPage);
        }

        /// <summary>
        /// HomePageViewModel。
        /// </summary>
        /// <param name="contentNavigationService">内容导航服务。</param>
        /// <param name="rootNavigationService">根导航服务。</param>
        public HomePageViewModel(IRootNavigationService rootNavigationService,
            IContentNavigationService contentNavigationService,
            IEventStorage eventStorage,
            IHistoryTodayService historyTodayService)
        {
            _rootNavigationService = rootNavigationService;
            _contentNavigationService = contentNavigationService;
            _eventStorage = eventStorage;
            _historyTodayService = historyTodayService;



            AnniversaryDayCollection = new InfiniteScrollCollection<Event>();
            CountdownDayCollection = new InfiniteScrollCollection<Event>();
            AllImportEventCollection = new InfiniteScrollCollection<Event>();

            //AnniversaryDayCollection.OnCanLoadMore = () => _canLoadMore;
            AnniversaryDayCollection.OnLoadMore = async () => {
                List<Event> annriversaryDayList = await _eventStorage.GetMemoryDaysAsync();

                List<Event> events = new List<Event>();
                foreach (var @event in annriversaryDayList)
                {
                    if (@event.IsImportant == 1)
                    {
                        events.Add(@event);
                    }
                }
                return events;
            };

            CountdownDayCollection.OnLoadMore = async () => {
                List<Event> countdownDayList = await _eventStorage.GetCountdownDaysAsync();

                List<Event> events = new List<Event>();
                foreach (var @event in countdownDayList)
                {
                    if (@event.IsImportant == 1)
                    {
                        events.Add(@event);
                    }
                }
                return events;
            };

            AllImportEventCollection.OnLoadMore = async () => {
                List<Event> annriversaryDayList =
                    await _eventStorage.GetMemoryDaysAsync();
                List<Event> countdownDayList =
                    await _eventStorage.GetCountdownDaysAsync();

                List<Event> events = new List<Event>();

                foreach (var @event in annriversaryDayList)
                {
                    if (@event.IsImportant == 1)
                    {
                        events.Add(@event);
                    }
                }
                foreach (var @event in countdownDayList)
                {
                    if (@event.IsImportant == 1)
                    {
                        events.Add(@event);
                    }
                }

                return events;
            };
        }


    }
}